package com.lanou3g.code0516;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/16;
 * Otherwise, I don't know who created it either
 */

@WebServlet(name = "MyUpServlet", urlPatterns = "/myup")
@MultipartConfig(maxFileSize = 1024 * 1024 * 100/*100M*/)
public class MyUpServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 上传文件
        // 根据表单中的 name属性,拿到要上传的文件
        // 在servlet3.0之后才有 -- 升级idea 自己就有了
        Part file = request.getPart("file");
        // file.getName 拿到的是在表单中的 name属性值
        System.out.println(file.getName());
        // 获取文件类型
        System.out.println(file.getContentType());
        // 获取文件大小
        System.out.println(file.getSize());
        // 获取文件详情
        System.out.println(file
                .getHeader("content-disposition"));


        File dir = new File(getServletContext().getRealPath("")
                + File.separator + "upload");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String fileName
                = getServletContext().getRealPath("")
                + File.separator + "upload" + File.separator
                + file.getName();

        file.write(fileName);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
